package com.qcu.controller;

import com.qcu.enity.LoginHistory;
import com.qcu.enity.User;
import com.qcu.service.LoginHistoryService;
import com.qcu.service.ServiceHolder;
import com.qcu.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @Name: MyComputer
 * @ClassName LoginController
 * @Description:
 * @date 2024/11/21 8:51
 */
@WebServlet("/loginUrl")
public class LoginController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private final UserService userService = ServiceHolder.userService;
    private final LoginHistoryService loginHistoryService = ServiceHolder.loginHistoryService;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginController() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String captchaExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        String captchaReceived = request.getParameter("captcha");

        if (!captchaExpected.equals(captchaReceived)) {
            // 验证码错误处理
            request.setAttribute("errorMessage", "验证码错误");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }
        // TODO Auto-generated method stub
        String username = request.getParameter("username");
        String password = request.getParameter("password");



        User res = userService.loginCheck(username, password);
        if(res != null) {
            //登录成功
            //添加记录
            LoginHistory loginHistory = new LoginHistory();
            loginHistory.setUserId(res.getUserId());
            loginHistory.setIp(request.getRemoteAddr());
            loginHistory.setCreateTime(new Date());
            loginHistoryService.addLoginHistory(loginHistory);
            //跳转
            request.getSession().setAttribute("loginUser", res);
            request.getRequestDispatcher("/mainUrl").forward(request, response);
        }else {
            //登录失败
            request.setAttribute("msg", "登录失败，请检查用户名和密码是否正确！");
            request.getRequestDispatcher("/pages/error.jsp").forward(request, response);
        }

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
